package com.codeape.number.ui.main.fragment.record;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;

import com.codeape.number.R;
import com.codeape.number.databinding.FragmentRecordsBinding;

import java.util.Objects;

/**
 * 记录Fragment
 *
 * @author LiuPeiming
 * Created at 2018/9/27 0:22
 */
public class RecordFragment extends Fragment {

    FragmentRecordsBinding binding = null;

    private View mInflaterView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (null != mInflaterView && null != mInflaterView.getParent()) {
            ViewGroup parent = (ViewGroup) mInflaterView.getParent();
            parent.removeView(mInflaterView);
            return mInflaterView;
        }

        mInflaterView = inflater.inflate(R.layout.fragment_records, container, false);

        binding = DataBindingUtil.bind(mInflaterView);
        assert binding != null;
        binding.setViewModel(new RecordViewModel(this));

//        binding.listRecords.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
//                //删除SQL语句
//                String sql = "delete from records where _id = " + mRecordsList.get(i).getId();
////                recordsDb.execSQL(sql);//执行删除语句
//                DatabaseUtils.getRecordsDb().execSQL(sql);//执行删除语句
//                mRecordsList.remove(i);
//                return false;
//            }
//        });

        return mInflaterView;


    }

    BroadcastReceiver mRefreshBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            assert action != null;
            if (action.equals("action.refreshData")) {
                RecordViewModel.name();
                RecordViewModel.mRecordsAdapter.set(new RecordViewModel.RecordsAdapter(getActivity(), RecordViewModel.mRecordsList));
            }
        }
    };

    @Override
    public void onStart() {
        super.onStart();
        Objects.requireNonNull(getActivity()).registerReceiver(mRefreshBroadcastReceiver, new IntentFilter("action.refreshData"));
    }

    @Override
    public void onStop() {
        super.onStop();
        Objects.requireNonNull(getActivity()).unregisterReceiver(mRefreshBroadcastReceiver);
    }

}